package com.zhouxiao.multithreading.线程执行顺序;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 周小哥  gqzmy@163.com 2023/3/3 22:21
 * <p>
 * 需求：
 * 1、1号线程、2号线程、3号线程都要执行
 * 2、执行是有顺序的，1->2->3
 * <p>
 * 实现：使用条件变量Condition，使线程顺序执行
 */

public class ThreadCondition {
    private static final Lock lock = new ReentrantLock();
    private static final Condition condition_1 = lock.newCondition();
    private static final Condition condition_2 = lock.newCondition();

    public static Boolean t1_run = false;
    public static Boolean t2_run = false;

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("1号线程");
                t1_run = true;
                condition_1.signal();
            } finally {
                lock.unlock();
            }

        });

        Thread thread2 = new Thread(() -> {
            lock.lock();
            try {
                if (!t1_run) {
                    System.out.println("1号线程还没有执行，2号线程要先等待");
                    condition_1.wait();
                }
                System.out.println("2号线程");
                t2_run = true;
                condition_2.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        });

        Thread thread3 = new Thread(() -> {
            lock.lock();
            try {
                if (!t2_run) {
                    System.out.println("2号线程还没有执行，3号线程要先等待");
                    condition_2.wait();
                }
                System.out.println("3号线程");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        });
        System.out.println("开始。。。");
        thread1.start();
        thread2.start();
        thread3.start();

    }
}
